package main

import "fmt"

func main() {
	head := &ListNode{Val: 1, Next: &ListNode{Val: 2, Next: &ListNode{Val: 3, Next: &ListNode{Val: 4, Next: &ListNode{Val: 5, Next: &ListNode{Val: 6}}}}}}
	head = rotateRight(head, 3)
	for ; head != nil; head = head.Next {
		fmt.Print(" ", head.Val)
	}
}

type ListNode struct {
	Val  int
	Next *ListNode
}

func rotateRight(head *ListNode, k int) *ListNode {
	if head == nil || head.Next == nil {
		return nil
	}
	length := 0
	tail := head
	for tail = head; tail.Next != nil; tail = tail.Next {
		length += 1
	}
	if k >= length {
		k = k - k%length
	}
	if k == 0 {
		return head
	}
	prev := head
	for i := 1; i < k; i++ {
		prev = prev.Next
	}
	next := prev.Next
	prev.Next = nil
	tail.Next = head
	head = next
	return head
}
